const app = getApp();
const pages = getCurrentPages();
const config = require('../config');
const { API_BASE_URL } = config;
const settlementPage = pages.find(page => page.route === 'pages/settlement/settlement');
if (settlementPage) {
  settlementPage.onCartChange();
}
Page({
  data: {
    total: 0,
    totalPrice: 0.0,
    isAllChecked: false,
    cartList: [],
    swipingItemId: null, // 记录正在滑动的商品的唯一标识，而不是索引
  },
  onLoad() {
    this.getCartList();
  },
  //获取购物车列表
  getCartList() {
    const that = this; // 保存this的引用，因为wx.request的回调函数中this指向会变化
    const token = wx.getStorageSync('token');
    console.log("存储 token:", token);

    if (!token) {
      console.warn('没有找到 token');
      return;
    }

    wx.request({
      url: `${API_BASE_URL}/shoppingCart/my/list/page/vo`, // 使用实际接口URL
      method: 'POST',
      data: {
        current: that.data.current,
        size: that.data.size
      },
      header: {
        'content-type': 'application/json', // 默认值是 application/json
        'satoken': token // 添加 token 到请求头
      },
      success(res) {
        const records = res.data.data.records || [];
        console.log("shoppingcartList:", records)
        that.setData({
          cartList: records,
          total: res.data.data.total, // 假设响应中有总记录数
          pages: res.data.data.pages  // 假设响应中有总页数
        });
        that.totalize();
        that.updateAllCheckedStatus();
      },
      fail(err) {
        console.error('网络请求失败', err);
      }
    });
  },

  // 更新全选按钮的状态
  updateAllCheckedStatus() {
    const cartList = this.data.cartList;
    const isAllChecked = cartList.every(item => item.choose);
    this.setData({
      isAllChecked
    });
  },
  // 删除商品函数
  deleteGood(itemId) {
    let cartList = this.data.cartList;
    const indexToRemove = cartList.findIndex(item => item._id === itemId);
    if (indexToRemove !== -1) {
      cartList.splice(indexToRemove, 1);
      this.setData({
        cartList
      });
      // 更新全局数据和缓存
      app.globalData.cartList = cartList;
      wx.setStorageSync('cartList', cartList);
      this.totalize();
      this.updateAllCheckedStatus();
    }
  },
  // 触摸开始
  touchStart(event) {
    // 记录起始位置
    this.startX = event.touches[0].clientX;
    // 记录正在滑动的商品的唯一标识
    this.swipingItemId = event.currentTarget.dataset.id;
  },
  // 触摸移动
  touchMove(event) {
    if (this.swipingItemId) {
      const moveX = event.touches[0].clientX;
      const deltaX = moveX - this.startX;
      if (Math.abs(deltaX) > 10) {
        this.setData({
          isSwiping: true
        });
      }
    }
  },
  // 触摸结束
  touchEnd(event) {
    if (this.data.isSwiping && this.swipingItemId) {
      // 删除对应的商品
      this.deleteGood(this.swipingItemId);
    }
    this.setData({
      isSwiping: false,
      swipingItemId: null
    });
  },
  // 点击增加按钮
  plusClick(event) {
    const index = event.currentTarget.dataset.index;
    const that = this; // 保存this的引用，因为wx.request的回调函数中this指向会变化
    const token = wx.getStorageSync('token');
    console.log("存储 token:", token);

    if (!token) {
      console.warn('没有找到 token');
      return;
    }

    wx.request({
      url: `${API_BASE_URL}/shoppingCart/edit`, // 使用实际接口URL
      method: 'POST',
      data: {
        productId: index,
        productSum: 1,
        checkAdd: true
      },
      header: {
        'content-type': 'application/json', // 默认值是 application/json
        'satoken': token // 添加 token 到请求头
      },
      success(res) {
        const records = res.data.data;
        console.log("checkSuess:", records)
        if(records){
          that.getCartList()
        }
      },
      fail(err) {
        console.error('网络请求失败', err);
      }
    });
  },
  // 点击减少按钮
  reduceClick(event) {
    const index = event.currentTarget.dataset.index;
    const that = this; // 保存this的引用，因为wx.request的回调函数中this指向会变化
    const token = wx.getStorageSync('token');
    console.log("存储 token:", token);

    if (!token) {
      console.warn('没有找到 token');
      return;
    }

    wx.request({
      url: `${API_BASE_URL}/shoppingCart/edit`, // 使用实际接口URL
      method: 'POST',
      data: {
        productId: index,
        productSum: 1,
        checkAdd: false
      },
      header: {
        'content-type': 'application/json', // 默认值是 application/json
        'satoken': token // 添加 token 到请求头
      },
      success(res) {
        const records = res.data.data;
        console.log("checkSuess:", records)
        if(records){
          that.getCartList()
        }
      },
      fail(err) {
        console.error('网络请求失败', err);
      }
    });
  },
  // 点击选择框
  checkboxClick(event) {
    const index = event.target.dataset.index;
    let cartList = this.data.cartList;
    cartList[index].choose = !cartList[index].choose;
    this.setData({
      "cartList": cartList
    });
    this.totalize();
    this.updateAllCheckedStatus();
  },
  // 结算函数
  totalize() {
    const cartList = this.data.cartList;
    console.log("Processing cart list:", cartList);

    // 使用 reduce 方法简化累加过程，并确保数值类型正确
    const result = cartList.reduce((acc, item, index) => {
      const good = item.productVO;

      // 检查并清理 productSum 和 price
      let productSumStr = good.productSum || '0'; // 如果不存在，则使用默认值 '0'
      let price = good.price || 0; // 如果不存在，则使用默认值 0

      let productSum = parseFloat(productSumStr.trim());

      if (isNaN(productSum) || isNaN(price)) {
        console.warn(`Item ${index} has invalid productSum or price:`, good);
        return acc; // 跳过这个商品
      }

      acc.total += productSum;
      acc.totalPrice += productSum * price;

      console.log(`Item ${index}: Product Sum=${productSum}, Price=${price}, Running Total=${acc.total}, Running Total Price=${acc.totalPrice}`);

      return acc;
    }, { total: 0, totalPrice: 0 });

    // 确保总价保留两位小数
    const formattedTotalPrice = parseFloat(result.totalPrice.toFixed(2));

    // 更新数据到组件状态或视图
    this.setData({
      "total": result.total,
      "totalPrice": formattedTotalPrice
    });
  },
  // 跳转到商品详情页
  toGoodDetail(event) {
    let id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/goodDetail/goodDetail?id=' + id,
    });
  },
  // 全选/全不选
  toggleAllChecked() {
    let cartList = this.data.cartList;
    const isAllChecked = !this.data.isAllChecked;
    cartList.forEach(item => {
      item.choose = isAllChecked;
    });
    this.setData({
      cartList,
      isAllChecked
    });
    this.totalize();
  },
  // 跳转到订单详情页 
  toOrder() {
    // 判断是否有选中的商品
    const cartList = this.data.cartList;
    const hasSelectedItem = cartList.some(item => item.choose);
    if (!hasSelectedItem) {
      wx.showToast({
        title: '请至少选择一个商品',
        icon: 'none'
      });
      return;
    }


    // 存储总数量
    wx.setStorageSync('total', this.data.total);
    const total = wx.getStorageSync('total');
    console.log(total);

    // 存储总价格
    wx.setStorageSync('totalPrice', this.data.totalPrice);
    const totalPrice = wx.getStorageSync('totalPrice');
    console.log(totalPrice);

    // 筛选出购物车中已选择的商品作为订单列表  
    const orderList = cartList.filter(item => item.choose && item.number > 0);
    wx.setStorageSync('orderList', orderList);
    wx.navigateTo({
      url: '/pages/orders/orders',
    });
  }
});